﻿Option Explicit On
Imports System.Windows.Forms

Public Class frmMain
    Private Sub MenuFileGrabAvito_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFileGrabAvito.Click
        'Проверяем лицензию
        If frmLicense.CheckLicense() <> 0 Then
            frmLicense.ShowDialog()
        End If
        'Выводим окно граббера
        Dim ChildForm As New frmAvito
        ChildForm.MdiParent = Me
        ChildForm.Show()
        'ChildForm.WindowState = FormWindowState.Maximized
    End Sub



    Private Sub MenuFileGrabMirkvartir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFileGrabMirkvartir.Click
        'Проверяем лицензию
        If frmLicense.CheckLicense() <> 0 Then
            frmLicense.ShowDialog()
        End If
        'Выводим окно граббера
        Dim ChildForm As New frmMirkvartir
        ChildForm.MdiParent = Me
        ChildForm.Show()
        'ChildForm.WindowState = FormWindowState.Maximized
    End Sub



    Private Sub MenuFileGrabIrr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFileGrabIrr.Click
        'Проверяем лицензию
        If frmLicense.CheckLicense() <> 0 Then
            frmLicense.ShowDialog()
        End If
        'Выводим окно граббера
        Dim ChildForm As New frmIrr
        ChildForm.MdiParent = Me
        ChildForm.Show()
        'ChildForm.WindowState = FormWindowState.Maximized
    End Sub



    Private Sub MenuFileGrabKomcity_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFileGrabKomcity.Click
        'Проверяем лицензию
        If frmLicense.CheckLicense() <> 0 Then
            frmLicense.ShowDialog()
        End If
        'Выводим окно граббера
        Dim ChildForm As New frmKomcity
        ChildForm.MdiParent = Me
        ChildForm.Show()
        'ChildForm.WindowState = FormWindowState.Maximized
    End Sub



    Private Sub MenuFileGrabFarpost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFileGrabFarpost.Click
        'Проверяем лицензию
        If frmLicense.CheckLicense() <> 0 Then
            frmLicense.ShowDialog()
        End If
        'Выводим окно граббера
        Dim ChildForm As New frmFarpost
        ChildForm.MdiParent = Me
        ChildForm.Show()
        'ChildForm.WindowState = FormWindowState.Maximized
    End Sub



    Private Sub MenuFileOpen_Click(ByVal sender As Object, ByVal e As EventArgs) Handles MenuFileOpen.Click, MenuFileOpen.Click
        Dim OpenFileDialog As New OpenFileDialog
        OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        OpenFileDialog.Filter = "Текстовые файлы (*.txt)|*.txt|Все файлы (*.*)|*.*"
        If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
            Dim FileName As String = OpenFileDialog.FileName
            ' TODO: добавьте здесь код открытия файла.
        End If
    End Sub



    Private Sub MenuFileSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFileSave.Click
        Dim SaveFileDialog As New SaveFileDialog
        Dim SavePath As String, SaveExt As String, ret As String = ""
        Dim activeChild As Object = Me.ActiveMdiChild

        If IsNothing(activeChild) Then
            MsgBox("Перед сохранением выберите окно граббера", MsgBoxStyle.Exclamation)
            Exit Sub
        End If

        With SaveFileDialog
            .Title = "Сохранить импорт"
            '.Filter = "Файл экспорта|*.xml|Страница HTML|*.html;*.htm"
            .Filter = "Файл импорта|*.xml"
            .InitialDirectory = Application.StartupPath & "\Import\"
            .FileName = activeChild.file_name
            If .ShowDialog() <> DialogResult.OK Then Exit Sub
            SavePath = .FileName
        End With

select_ext:
        SaveExt = SavePath.Substring(SavePath.LastIndexOf(".") + 1).ToLower
        Select Case SaveExt
            Case "html", "htm"
                'Получаем HTML код
                Dim web As WebBrowser = activeChild.Controls.Find("web", True)(0)
                ret = web.DocumentText

                'Записываем все в файл
                Try
                    IO.File.WriteAllText(SavePath, ret, System.Text.Encoding.Default)
                Catch ex As Exception
                    MsgBox(ex.Message, MsgBoxStyle.Exclamation)
                End Try

            Case "xml"
                Dim adverts() As AdvertType
                Dim tpl_main As String, tpl_row As String, rows As String = ""
                Dim parse As Object, n As Integer
                adverts = activeChild.getAdverts()

                'Загружаем шаблоны
                tpl_main = TplLoad("import.tpl", System.Text.Encoding.UTF8)
                tpl_row = TplLoad("import.row.tpl", System.Text.Encoding.UTF8)

                If IsNothing(adverts) Then
                ElseIf Not (IsArray(adverts)) Then
                ElseIf adverts.Length = 0 Then
                Else
                    For n = 0 To UBound(adverts)
                        parse = Nothing
                        TplAddParse(parse, "url", adverts(n).url)
                        TplAddParse(parse, "street", adverts(n).street)
                        TplAddParse(parse, "nomer", adverts(n).nomer)
                        TplAddParse(parse, "building", adverts(n).building)
                        TplAddParse(parse, "balkon", adverts(n).balkon)
                        TplAddParse(parse, "floor", adverts(n).floor)
                        TplAddParse(parse, "floor_all", adverts(n).floor_all)
                        TplAddParse(parse, "kvm_all", adverts(n).kvm_all)
                        TplAddParse(parse, "kvm_live", adverts(n).kvm_live)
                        TplAddParse(parse, "kvm_kitchen", adverts(n).kvm_kitchen)
                        TplAddParse(parse, "price", adverts(n).price)
                        TplAddParse(parse, "content", adverts(n).content)
                        TplAddParse(parse, "text", adverts(n).text)
                        TplAddParse(parse, "phone", Join(adverts(n).phone, "|"))
                        'Парсим объект
                        rows &= TplParcer(tpl_row, parse)
                    Next
                End If

                'Парсим главный шаблон
                parse = Nothing
                TplAddParse(parse, "adv_name", activeChild.ADV_NAME)
                TplAddParse(parse, "catalog", activeChild.catalog_name)
                TplAddParse(parse, "rows", rows)
                ret = TplParcer(tpl_main, parse)

                'Записываем все в файл
                Try
                    IO.File.WriteAllText(SavePath, ret, System.Text.Encoding.UTF8)
                Catch ex As Exception
                    MsgBox(ex.Message, MsgBoxStyle.Exclamation)
                End Try


                'Сохраняем также HTML файл
                ret = SavePath.Substring(0, SavePath.LastIndexOf("\") + 1)
                ret = ret & "HTML\"
                ret = ret & SavePath.Substring(SavePath.LastIndexOf("\") + 1)
                ret = ret.Substring(0, ret.LastIndexOf(".") + 1) & "html"
                SavePath = ret
                GoTo select_ext
        End Select
    End Sub



    Private Sub MenuFile_MakeExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFile_MakeExcelFile.Click
        frmSelectXmlFile.MdiParent = Me
        frmSelectXmlFile.Show()
    End Sub



    Private Sub MenuFilePrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFilePrint.Click
        Dim activeChild As Form = Me.ActiveMdiChild
        Dim web As WebBrowser = activeChild.Controls.Find("web", True)(0)
        web.ShowPrintDialog()
    End Sub



    Private Sub MenuFileExit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles MenuFileExit.Click
        Me.Close()
    End Sub



    Private Sub MenuDBPhoneAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuDBPhoneAdd.Click
        frmPhoneAdd.txtEstates.Text = ""
        frmPhoneAdd.ShowDialog(Me)
        If frmPhoneAdd.enter_phones = True Then
            DBEstate_AddEstate(frmPhoneAdd.phones)
        End If
    End Sub



    Private Sub CascadeToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles CascadeToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.Cascade)
    End Sub
    Private Sub TileVerticalToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles TileVerticalToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.TileVertical)
    End Sub
    Private Sub TileHorizontalToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles TileHorizontalToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.TileHorizontal)
    End Sub
    Private Sub ArrangeIconsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ArrangeIconsToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.ArrangeIcons)
    End Sub
    Private Sub CloseAllToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles CloseAllToolStripMenuItem.Click
        ' Закрыть все дочерние формы указанного родителя.
        For Each ChildForm As Form In Me.MdiChildren
            ChildForm.Close()
        Next
    End Sub



    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Dim ChildForm As New frmKomcity
        'ChildForm.MdiParent = Me
        'ChildForm.Show()
        'Exit Sub
        
        'Проверяем лицензию
        frmLicense.Init()
        If frmLicense.CheckLicense() <> 0 Then
            frmLicense.ShowDialog()
        End If

        'If MsgBox("Загрузить базу риэлторов с сайта?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question) = MsgBoxResult.Yes Then
        '    Dim wbc As New System.Net.WebClient
        '    Dim response As String
        '    Dim phones() As String
        '    Dim phone As String

        '    wbc.Encoding = System.Text.Encoding.UTF8

        '    Try : response = wbc.DownloadString(SITE_MG & "data/get_base/")
        '    Catch ex As Exception
        '        MsgBox("Страница не получена. " & ex.Message, MsgBoxStyle.Exclamation) : Exit Sub
        '    End Try
        '    phones = Split(response, vbLf)

        '    ConnectDB() 'подключаемся к базе данных

        '    'Отчищаем свою базу риэлторов
        '    Dim rc As OleDb.OleDbCommand
        '    rc = New OleDb.OleDbCommand("Delete * From `estate_phones`", oDBConn)
        '    rc.ExecuteNonQuery()

        '    For n = 1 To UBound(phones)
        '        phone = Split(phones(n), "|")(1)
        '        rc = New OleDb.OleDbCommand("INSERT INTO `estate_phones` (`phone`) VALUES ('" & phone & "')", oDBConn)
        '        rc.ExecuteNonQuery()
        '    Next n

        '    MsgBox("База риэлторов успешно загружена", MsgBoxStyle.Information)
        'End If
    End Sub

    'Форма закрылась
    Private Sub frmMain_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        CloseDB()
    End Sub

End Class